﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Services;
using BSPortal.Entity;


namespace BSPortal
{
    /// <summary>
    /// Summary description for MainService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class MainService : WebService
    {
        #region Manage Session

        [WebMethod(EnableSession = true, CacheDuration = 120)]
        public int Login(string username, string password)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                password = GetMD5Hash(password);
                var user = (from row in DataContext.Users
                            where row.Username == username && row.Password == password
                            select row).First();

                if (user == null)
                {
                    return (int) Common.RetCode.FAIL;
                }
                {

                    System.Web.HttpContext.Current.Session["Username"] = username;
                    System.Web.HttpContext.Current.Session["IsLogin"] = true;
                    System.Web.HttpContext.Current.Session["UserType"] = user.Type;
                    System.Web.HttpContext.Current.Session[PageConst.ClientService] = this;
                    return (int) Common.RetCode.SUCESS;
                }
            }
            catch (Exception exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true, CacheDuration = 120)]
        public int Logout()
        {

            if (System.Web.HttpContext.Current.Session["Username"] == null ||
                System.Web.HttpContext.Current.Session["IsLogin"] == null)
            {
                return (int) Common.RetCode.FAIL;
            }
            System.Web.HttpContext.Current.Session.Abandon();
            return (int) Common.RetCode.SUCESS;
        }

        [WebMethod(EnableSession = true, CacheDuration = 120)]
        public int IsLogin()
        {
            if (System.Web.HttpContext.Current.Session["Username"] == null ||
                System.Web.HttpContext.Current.Session["IsLogin"] == null)
            {
                return (int) Common.RetCode.FAIL;
            }
            return (int) Common.RetCode.SUCESS;
        }

        public string GetMD5Hash(string input)
        {
            var x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
            bs = x.ComputeHash(bs);
            var s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            string password = s.ToString();
            return password;
        }

        #endregion

        #region Manage Category
        [WebMethod(EnableSession = true)]
        public int CreateCateogry(string name, string image, int parentCategory, bool isPublished)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var category = new Category {Name = name, Image = image, ParentCategory = (short) parentCategory, IsPublished = isPublished};
                DataContext.Categories.InsertOnSubmit(category);
                DataContext.SubmitChanges();
                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int UpdateCategory(short id, string name, string image, short parentCategory, bool isPublished)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var category = (from row in DataContext.Categories
                                where row.CategoryId == id
                                select row).First();

                if (category == null)
                {
                    return (int) Common.RetCode.INCORRECT_CATEGORY;
                }

                category.Name = name;
                category.Image = image;
                category.ParentCategory = parentCategory;
                category.IsPublished = isPublished;

                DataContext.SubmitChanges();
                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int DeleteCategory(short id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var category = (from row in DataContext.Categories
                                where row.CategoryId == id
                                select row).First();

                if (category == null)
                {
                    return (int) Common.RetCode.INCORRECT_CATEGORY;
                }

                DataContext.Categories.DeleteOnSubmit(category);
                DataContext.SubmitChanges();

                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod]
        public Category GetCategoryById(short id)
        {
            try
            {
                OnlineShopDataContext DataContext = new OnlineShopDataContext();
                var category = (from row in DataContext.Categories
                                where row.CategoryId == id
                                select row).First();

                return category;
            }
            catch (Exception)
            {
                return null;
            }
        }
        [WebMethod]
        public Category GetCategoryByName(string name)
        {
            try
            {
                OnlineShopDataContext DataContext = new OnlineShopDataContext();
                var category = (from row in DataContext.Categories
                                where row.Name == name
                                select row).First();

                return category;
            }
            catch (Exception)
            {
                return null;
            }
        }

        [WebMethod]
        public List<Category> GetListChildCategoryByParent(short parentCategory)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var categories = from row in DataContext.Categories
                                 where row.ParentCategory.Value == parentCategory
                                 orderby row.Name
                                 select row;
                return categories.ToList();
            }
            catch (Exception ex)
            {
                return new List<Category>();
            }
        }

        [WebMethod]
        public List<Category> GetListAllCategory()
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var categories = from row in DataContext.Categories
                                 orderby row.Name
                                 select row;
                return categories.ToList();
            }
            catch (Exception ex)
            {
                return new List<Category>();
            }
        }

        [WebMethod]
        public List<Category> GetAllCategoryTreeView(short parrentCategory)
        {
            var result = new List<Category>();
            var childrent1 = GetListChildCategoryByParent(parrentCategory);
            result.AddRange(childrent1);
            foreach (var category in childrent1)
            {
                var childrent2 = GetAllCategoryTreeView(category.CategoryId);
                if(childrent2.Count>0)
                    result.AddRange(childrent2);
            }
            return result;
        }


        [WebMethod]
        public List<Category> GetListAllCategoryByParent(short parrentCategory)
        {
            if (parrentCategory == 0)
                return GetListAllCategory();

            var result = new List<Category>();
            var childrent1 = GetListChildCategoryByParent(parrentCategory);

            result.AddRange(childrent1);

            foreach (var category in childrent1)
            {
                var childrent2 = GetListAllCategoryByParent(category.CategoryId);
                result.AddRange(childrent2);
            }

            return result;
        }

        [WebMethod]
        public List<Category> GetListSecondLevelCategory(short line)
        {
            var childrent1 = GetListChildCategoryByParent(line).Select(cat=>cat.CategoryId).ToList();

            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            var childrent2 = from row in DataContext.Categories
                             where childrent1.Contains((short)row.ParentCategory)
                             orderby row.Name
                             select row;

            return childrent2.ToList();
        }

        #endregion

        #region Manage Writer

        [WebMethod(EnableSession = true)]
        public int CreateWriter(string name, string resume, string image, bool isPublished)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var writer = new Writer { Name = name, Resume = resume, Image = image, IsPublished = isPublished };

                DataContext.Writers.InsertOnSubmit(writer);
                DataContext.SubmitChanges();

                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int UpdateWriter(short id, string name, string resume, string image, bool isPublished)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var writer = (from row in DataContext.Writers
                              where row.WriterId == id
                              select row).First();

                if (writer == null)
                {
                    return (int) Common.RetCode.INCORRECT_WRITER;
                }

                writer.Name = name;
                writer.Resume = resume;
                writer.IsPublished = isPublished;
                writer.Image = image;

                DataContext.SubmitChanges();
                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int DeleteWriter(short id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var writer = (from row in DataContext.Writers
                              where row.WriterId == id
                              select row).First();

                if (writer == null)
                {
                    return (int) Common.RetCode.INCORRECT_WRITER;
                }

                DataContext.Writers.DeleteOnSubmit(writer);
                DataContext.SubmitChanges();

                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod]
        public Writer GetWriterById(short id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();

            var writer = (from row in DataContext.Writers
                          where row.WriterId == id
                          select row).First();

            return writer;
        }

        [WebMethod]
        public List<Writer> GetAllWriter()
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var writers = from row in DataContext.Writers
                              orderby row.Name
                              select row;
                return writers.ToList();
            }
            catch (Exception)
            {
                return new List<Writer>();
            }
        }
        [WebMethod]
        public List<Writer> GetListWriterConditionLikeName(string likeName)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var writers = from row in DataContext.Writers
                              where row.Name.IndexOf(likeName)>=0
                              orderby row.Name
                              select row;
                return writers.ToList();
            }
            catch (Exception)
            {
                return new List<Writer>();
            }
        }

        #endregion

        #region Manage Publisher

        [WebMethod(EnableSession = true)]
        public int CreatePublisher(string name, string image, short categoryId, bool isPublished)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var publisher = new Publisher {Name = name, Image = image, CategoryId = categoryId, IsPublished = isPublished};

                DataContext.Publishers.InsertOnSubmit(publisher);
                DataContext.SubmitChanges();

                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int UpdatePublisher(short id, string name, string image, short? categoryId, bool isPublished)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var publisher = (from row in DataContext.Publishers
                                 where row.PublisherId == id
                                 select row).First();

                if (publisher == null)
                {
                    return (int) Common.RetCode.INCORRECT_PUBLISHER;
                }

                publisher.Name = name;
                publisher.Image = image;
                publisher.CategoryId = categoryId;
                publisher.IsPublished = isPublished;

                DataContext.SubmitChanges();
                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int DeletePublisher(short id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var publisher = (from row in DataContext.Publishers
                                 where row.PublisherId == id
                                 select row).First();

                if (publisher == null)
                {
                    return (int) Common.RetCode.INCORRECT_PUBLISHER;
                }

                DataContext.Publishers.DeleteOnSubmit(publisher);
                DataContext.SubmitChanges();

                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod]
        public Publisher GetPublisherById(short id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            var publisher = (from row in DataContext.Publishers
                             where row.PublisherId == id
                             select row).First();

            return publisher;
        }

        [WebMethod]
        public List<Publisher> GetListPublisherByCategory(short categoryId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var publishers = from row in DataContext.Publishers
                                 where row.CategoryId == categoryId
                                 orderby row.Name
                                 select row;

                return publishers.ToList();
            }
            catch (Exception)
            {
                return new List<Publisher>();
            }
        }


        [WebMethod]
        public List<Publisher> GetListPublisherConditionLikeName(string likeName, short categoryId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var publishers = from row in DataContext.Publishers
                                 where (row.Name.IndexOf(likeName) >= 0 && row.CategoryId==categoryId)
                                 orderby row.Name
                                 select row;

                return publishers.ToList();
            }
            catch (Exception)
            {
                return new List<Publisher>();
            }
        }

        #endregion

        #region Manage User

        [WebMethod]
        public List<User> GetListUserConditionLikeName(string likeName)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var htmlContent = from row in DataContext.Users
                                  where row.Name.IndexOf(likeName) >= 0 || row.Username.IndexOf(likeName) >= 0
                                  select row;
                return htmlContent.ToList();
            }
            catch (Exception)
            {
                return new List<User>();
            }
        }

        [WebMethod(EnableSession = true)]
        public int CreateUser(string username, string password, string name, string address, string email, string phone,
                              int type, int city, int district, int ward)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var user = new User
                               {
                                   Username = username,
                                   Password = GetMD5Hash(password),
                                   Name = name,
                                   Address = address,
                                   CreatedDate = DateTime.Now,
                                   Email = email,
                                   LastLoginDate = DateTime.Now,
                                   UpdateDate = DateTime.Now,
                                   UpdateUser =
                                       (System.Web.HttpContext.Current.Session["Username"] != null) ? System.Web.HttpContext.Current.Session["Username"].ToString() : "",
                                   Phone = phone,
                                   Type = type,
                                   City = city,
                                   District = district,
                                   Ward = ward
                               };

                DataContext.Users.InsertOnSubmit(user);
                DataContext.SubmitChanges();

                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int UpdateUser(string username, string name, string address, string email, string phone, int type, int city, int district, int ward)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN && _loginUser.Username != username)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var user = (from row in DataContext.Users
                            where row.Username == username
                            select row).First();

                if (user == null)
                {
                    return (int) Common.RetCode.INCORRECT_USERNAME;
                }

                user.Name = name;
                user.Address = address;
                user.Email = email;
                user.Phone = phone;
                user.Type = type;
                user.City = city;
                user.District = district;
                user.Ward = ward;
                user.UpdateDate = DateTime.Now;
                user.UpdateUser = _loginUser.Username;

                DataContext.SubmitChanges();
                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int ChangePassword(string username, string password)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN && _loginUser.Username != username)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var user = (from row in DataContext.Users
                            where row.Username == username
                            select row).First();

                if (user == null)
                {
                    return (int)Common.RetCode.INCORRECT_USERNAME;
                }

                user.Password = GetMD5Hash(password);
                
                user.UpdateDate = DateTime.Now;
                user.UpdateUser = _loginUser.Username;

                DataContext.SubmitChanges();
                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int DeleteUser(string id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var user = (from row in DataContext.Users
                            where row.Username == id
                            select row).First();

                if (user == null)
                {
                    return (int) Common.RetCode.INCORRECT_USERNAME;
                }

                DataContext.Users.DeleteOnSubmit(user);
                DataContext.SubmitChanges();

                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod]
        public User GetUserById(string id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var user = (from row in DataContext.Users
                            where row.Username == id
                            select row).First();
                return user;
            }
            catch (Exception exception)
            {
                return null;
            }
        }

        [WebMethod]
        public List<User> GetAllUser()
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var users = from row in DataContext.Users
                            select row;
                return users.ToList();
            }
            catch (Exception)
            {
                return new List<User>();
            }
        }

        #endregion

        #region Manage Product

        [WebMethod(EnableSession = true)]
        public int CreateProduct(string name, string title, string content, float price, float discount, string image,
                                 short categoryId, short writerId, short publisherId, int rate, double Tranformfee,string technicInfo, bool isPublished, string distributor)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var category = GetCategoryById(categoryId);
                if (category == null)
                {
                    return (int) Common.RetCode.INCORRECT_CATEGORY;
                }

                if (writerId != 0)
                {
                    var writer = GetWriterById(writerId);
                    if (writer == null)
                    {
                        return (int)Common.RetCode.INCORRECT_WRITER;
                    }
                }

                var product = new Product();
                product.ProductId = 1;
                product.Name = name;
                product.Content = content;
                product.CategoryId = categoryId;
                product.Image = image;
                product.CreatedDate = DateTime.Now;
                product.Price = price;
                product.Discount = discount;
                product.PublisherId = publisherId;
                product.Rate = rate;
                product.ReadTime = 0;
                product.SoldAmount = 0;
                product.WriterId = writerId;
                product.UpdatedDate = DateTime.Now;
                product.Tranformfee = Tranformfee;
                product.TechnicInfo = technicInfo;
                product.IsPublished = isPublished;
                product.Distributor = distributor;
                DataContext.Products.InsertOnSubmit(product);
                DataContext.SubmitChanges();

                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int UpdateProduct(short id, string name, string image, string title, string content, double price,
                                 int rate, short categoryId, short publisherId, short writerId, float discount, double tranformFee, string distributor, string technicInfo, bool isPublished)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var product = (from row in DataContext.Products
                               where row.ProductId == id
                               select row).First();

                if (product == null)
                {
                    return (int) Common.RetCode.INCORRECT_PRODUCT;
                }

                product.Name = name;
                product.Content = content;
                product.Image = image;
                product.Price = price;
                product.Discount = discount;
                product.Rate = rate;
                product.CategoryId = categoryId;
                product.PublisherId = publisherId;
                product.WriterId = writerId;
                product.UpdatedDate = DateTime.Now;
                product.Tranformfee = tranformFee;
                product.TechnicInfo = technicInfo;
                product.IsPublished = isPublished;
                product.Distributor = distributor;
                DataContext.SubmitChanges();
                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int DeleteProduct(short id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var product = (from row in DataContext.Products
                               where row.ProductId == id
                               select row).First();

                if (product == null)
                {
                    return (int) Common.RetCode.INCORRECT_PRODUCT;
                }

                DataContext.Products.DeleteOnSubmit(product);
                DataContext.SubmitChanges();

                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod]
        public Product GetProductById(short id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            var product = (from row in DataContext.Products
                           where row.ProductId == id
                           select row).First();

            return product;
        }

        [WebMethod]
        public List<Product> GetListProductByCategoryId(short categoryId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var products = from row in DataContext.Products
                               where row.CategoryId == categoryId
                               orderby row.Name
                               select row;
                return products.ToList();
            }
            catch (Exception)
            {
                return new List<Product>();
            }
        }

        [WebMethod]
        public List<Product> GetListProductByListCategoryId(List<short> listCategoryId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var products = from row in DataContext.Products
                               where listCategoryId.Contains(row.CategoryId)
                               orderby row.Name
                               select row;
                return products.ToList();
            }
            catch (Exception)
            {
                return new List<Product>();
            }
        }

        [WebMethod]
        public List<Product> GetListLastestProductByCategoryId(short categoryId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var listCategoryId = GetListAllCategoryByParent(categoryId).Select(row => row.CategoryId).ToList();
                var products = from row in DataContext.Products
                               where listCategoryId.Contains(row.CategoryId)
                               orderby row.CreatedDate descending
                               select row;
                return products.ToList();
            }
            catch (Exception)
            {
                return new List<Product>();
            }
        }

        [WebMethod]
        public List<Product> GetListProductConditionLikeName(string para, List<short> listCategory)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var products = from row in DataContext.Products
                               where (row.Name.IndexOf(para) >= 0 && listCategory.Contains(row.CategoryId))
                               orderby row.Name
                               select row;
                return products.ToList();
            }
            catch (Exception)
            {
                return new List<Product>();
            }
        }

        [WebMethod]
        public List<Product> GetSamProduct(short productId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var product = GetProductById(productId);

                var products = from row in DataContext.Products
                               where row.CategoryId == product.CategoryId
                               && row != product
                               orderby row.Name
                               select row;
                return products.ToList();
            }
            catch (Exception)
            {
                return new List<Product>();
            }
        }

        [WebMethod]
        public List<Product> GetListProductByWriterId(short writerId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var products = from row in DataContext.Products
                               where row.WriterId == writerId
                               orderby row.Name
                               select row;
                return products.ToList();
            }
            catch (Exception)
            {
                return new List<Product>();
            }
        }

        [WebMethod]
        public List<Product> GetListProductByCondition(string name, short categoryId, int discount, int price)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                List<Category> listCategory = GetListChildCategoryByParent(categoryId);
                Category category = GetCategoryById(categoryId);
                listCategory.Add(category);
                var categories = listCategory.Select(cat => cat.CategoryId).ToList();

                listCategory.Add(category);

                var listProduct = from row in DataContext.Products
                                  where row.Name.Contains(name)
                                        && categories.Contains(row.CategoryId)
                                        && ((price <= 0) || row.Price <= price)
                                        &&
                                        ((discount == 3) || (discount == 1 && row.Discount > 0) ||
                                         (discount == 2 && row.Discount <= 0))
                                  orderby row.Name
                                  select row;

                return listProduct.ToList();
            }
            catch (Exception exception)
            {
                return new List<Product>();
            }
        }

        [WebMethod]
        public List<Product> GetListProductByPublisherId(short publisherId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var products = from row in DataContext.Products
                               where row.PublisherId == publisherId
                               orderby row.Name
                               select row;
                return products.ToList();
            }
            catch (Exception)
            {
                return new List<Product>();
            }
        }

        [WebMethod]
        public List<Product> GetListTopSellProduct(short categoryId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var listCategory = new List<Category>();
                switch (categoryId)
                {
                    case 1:
                    case 2:
                    case 3:
                        listCategory = GetListAllCategoryByParent(categoryId);
                        break;
                    default:
                        listCategory = GetListAllCategory();
                        break;
                }

                var categories = listCategory.Select(category => category.CategoryId).ToList();
                var products = (from row in DataContext.Products
                                where categories.Contains(row.CategoryId)
                                orderby row.SoldAmount descending
                                select row).Take(8);
                return products.ToList();
            }
            catch (Exception)
            {
                return new List<Product>();
            }
        }

        [WebMethod]
        public List<Product> GetListDiscountProduct(short categoryId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var listCategory = new List<Category>();
                switch (categoryId)
                {
                    case 1:
                    case 2:
                    case 3:
                        listCategory = GetListAllCategoryByParent(categoryId);
                        break;
                    default:
                        listCategory = GetListAllCategory();
                        break;
                }

                var categories = listCategory.Select(category => category.CategoryId).ToList();
                var products = from row in DataContext.Products
                               where row.Discount > 0
                                     && categories.Contains(row.CategoryId)
                               orderby row.Discount descending
                               select row;

                return products.ToList();
            }
            catch (Exception)
            {
                return new List<Product>();
            }
        }

        [WebMethod]
        public List<Product> GetListTopReadProduct(short categoryId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var listCategory = new List<Category>();
                switch (categoryId)
                {
                    case 1:
                    case 2:
                    case 3:
                        listCategory = GetListAllCategoryByParent(categoryId);
                        break;
                    default:
                        listCategory = GetListAllCategory();
                        break;
                }

                var categories = listCategory.Select(category => category.CategoryId).ToList();
                var products = (from row in DataContext.Products
                                where categories.Contains(row.CategoryId)
                                orderby row.ReadTime descending
                                select row).Take(8);
                return products.ToList();
            }
            catch (Exception)
            {
                return new List<Product>();
            }
        }

        [WebMethod]
        public Product GetFullProduct(Product product)
        {
            var category = GetCategoryById(product.CategoryId);
            product.CategoryName = category.Name;
            
            if (product.PublisherId != null)
            {
                var publisher = GetPublisherById((short)product.PublisherId);
                product.PublisherName = publisher.Name;
            }

            if (product.WriterId != null && product.WriterId != 0)
            {
                var writer = GetWriterById((short) product.WriterId);
                product.WiterName = writer.Name;
            }

            return product;
        }

        public Product GetFullProductById(short productId)
        {
            var product = GetProductById(productId);
            var category = GetCategoryById(product.CategoryId);
            product.CategoryName = category.Name;

            var publisher = GetPublisherById((short)product.PublisherId);
            product.PublisherName = publisher.Name;

            if (product.WriterId != null)
            {
                var writer = GetWriterById((short)product.WriterId);
                product.WiterName = writer.Name;
            }

            return product;
        }

        [WebMethod]
        public List<Product> GetListFullProduct(List<Product> listProduct)
        {
            var result = new List<Product>();
            foreach (var product in listProduct)
            {
                result.Add(GetFullProduct(product));
            }

            return result.OrderBy(row=>row.Name).ToList();
        }

        [WebMethod(EnableSession = true)]
        public int SetReadTime(short id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var product = (from row in DataContext.Products
                               where row.ProductId == id
                               select row).First();

                if (product == null)
                {
                    return (int) Common.RetCode.INCORRECT_PRODUCT;
                }

                product.ReadTime++;

                DataContext.SubmitChanges();
                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int SetSoldTime(short id, short amount)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {                
                var product = (from row in DataContext.Products
                               where row.ProductId == id
                               select row).First();

                if (product == null)
                {
                    return (int) Common.RetCode.INCORRECT_PRODUCT;
                }

                product.SoldAmount += amount;

                DataContext.SubmitChanges();
                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public List<Product> GetListProductByKey(short categoryId, string key)
        {
            var listCategory = GetListAllCategoryByParent(categoryId).Select(cat => cat.CategoryId).ToList();
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            var result = from product in DataContext.Products
                         where listCategory.Contains(product.CategoryId)
                         join category in DataContext.Categories on product.CategoryId equals category.CategoryId
                         where product.Name.Contains(key) || product.Content.Contains(key)
                         orderby product.Name
                         select product;

            return result.ToList();
        }
        #endregion

        #region Manage Order

        [WebMethod(EnableSession = true)]
        public int CreateOrder(string name, string address, string email, string note, string phoneNumber,
                               string transportType, float fee, int payType, int city, int district, int ward)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    var checkUser = GetUserById(email);
                    if (checkUser == null)
                    {
                        var user = new User
                                       {
                                           Username = email,
                                           Password = GetMD5Hash(phoneNumber),
                                           Name = name,
                                           Address = address,
                                           CreatedDate = DateTime.Now,
                                           Email = email,
                                           LastLoginDate = DateTime.Now,
                                           UpdateDate = DateTime.Now,
                                           Phone = phoneNumber,
                                           Type = (int) Common.UserType.CUSTOMER,
                                           City = city,
                                           District = district,
                                           Ward = ward
                                       };

                        DataContext.Users.InsertOnSubmit(user);
                        DataContext.SubmitChanges();
                    }

                    Login(email, phoneNumber);
                }

                var order = new Order
                                {
                                    Name = name,
                                    Address = address,
                                    CreatedDate = DateTime.Now,
                                    Note = note,
                                    Phone = phoneNumber,
                                    Status = 0,
                                    ExcecutedUser = "",
                                    Username = System.Web.HttpContext.Current.Session["Username"].ToString(),
                                    TransportType = transportType,
                                    UpdatedDate = DateTime.Now,
                                    Fee = fee,
                                    PayType = payType
                                };

                DataContext.Orders.InsertOnSubmit(order);
                DataContext.SubmitChanges();

                return order.OrderId;
            }
            catch (Exception)
            {
                return 0;
            }
        }

        [WebMethod(EnableSession = true)]
        public int UpdateOrder(short id, string name, string address, string note, string phoneNumber,
                               string transportType, float fee, int payType, int status, int city, int district, int ward)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var order = (from row in DataContext.Orders
                             where row.OrderId == id
                             select row).First();

                if (order == null)
                {
                    return (int) Common.RetCode.INCORRECT_ORDER;
                }

                order.Name = name;
                order.Address = address;
                order.UpdatedDate = DateTime.Now;
                order.Note = note;
                order.Phone = phoneNumber;
                order.Status = status;
                order.ExcecutedUser = System.Web.HttpContext.Current.Session["Username"].ToString();
                order.TransportType = transportType;
                order.Fee = fee;
                order.PayType = payType;
                order.City = city;
                order.District = district;
                order.Ward = ward;

                DataContext.SubmitChanges();
                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int UpdateOrder(short id, string note)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var order = (from row in DataContext.Orders
                             where row.OrderId == id
                             select row).First();

                if (order == null)
                {
                    return (int)Common.RetCode.INCORRECT_ORDER;
                }

                order.UpdatedDate = DateTime.Now;
                order.Note = note;

                DataContext.SubmitChanges();
                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int SetOrderStatus(short id, int status)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var order = (from row in DataContext.Orders
                             where row.OrderId == id
                             select row).First();

                if (order == null)
                {
                    return (int) Common.RetCode.INCORRECT_ORDER;
                }

                order.Status = status;
                order.ExcecutedUser = System.Web.HttpContext.Current.Session["Username"].ToString();

                DataContext.SubmitChanges();
                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int DeleteOrder(short id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var order = (from row in DataContext.Orders
                             where row.OrderId == id
                             select row).First();

                if (order == null)
                {
                    return (int) Common.RetCode.INCORRECT_ORDER;
                }

                DataContext.Orders.DeleteOnSubmit(order);
                DataContext.SubmitChanges();

                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod]
        public Order GetOrderById(short id)
        {
            var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
            if (_loginUser.Type != (int) Common.UserType.ADMIN)
                return null;
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            var order = (from row in DataContext.Orders
                         where row.OrderId == id
                         select row).First();

            return order;
        }

        [WebMethod]
        public List<Order> GetAllOrder()
        {
            var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
            if (_loginUser.Type != (int) Common.UserType.ADMIN)
                return null;
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var orders = from row in DataContext.Orders
                             select row;
                return orders.ToList();
            }
            catch (Exception)
            {
                return new List<Order>();
            }
        }

        [WebMethod]
        public List<Order> GetOrderByConditions(DateTime fromDate, DateTime toDate, string username, string address, string phone, string name, int status, int? city, int? district, int? ward)
        {
            var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
            if (_loginUser.Type != (int) Common.UserType.ADMIN)
                return null;

            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var orders = from row in DataContext.Orders
                             where row.Status == status
                                   && row.CreatedDate >= fromDate.AddDays(-1)
                                   && row.CreatedDate <= toDate.AddDays(1)
                                   && (row.Username.Contains(username)
                                       || row.Phone.Contains(phone)
                                       || row.Name.Contains(name)
                                       || row.Address.Contains(address))
                                       &&(city < 0 || row.City ==city)
                                       && (district < 0 || row.District == district)
                                       && (ward < 0 || row.Ward == ward)
                             select row;
                return orders.ToList();
            }
            catch (Exception)
            {
                return new List<Order>();
            }
        }

        #endregion

        #region Manage OrderDetail

        [WebMethod(EnableSession = true)]
        public int CreateOrderDetail(short orderId, short amount, short productId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var product = GetProductById(productId);
                if (product == null)
                    return (int) Common.RetCode.INCORRECT_PRODUCT;

                var orderDetails = GetListOrderDetailByOrderId(orderId);
                if (orderDetails.Any(detail => detail.ProductId == productId))
                {
                    return (int) Common.RetCode.EXSITPRODUCT;
                }

                var orderDetail = new OrderDetail {OrderId = orderId, Amount = amount, ProductId = productId};

                SetSoldTime(productId, amount);

                DataContext.OrderDetails.InsertOnSubmit(orderDetail);
                DataContext.SubmitChanges();

                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int UpdateOrderDetail(short id, short amount, short productId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var orderDetail = (from row in DataContext.OrderDetails
                                   where row.OrderDetailId == id
                                   select row).First();

                if (orderDetail == null)
                {
                    return (int) Common.RetCode.INCORRECT_PUBLISHER;
                }

                orderDetail.Amount = amount;
                orderDetail.ProductId = productId;

                DataContext.SubmitChanges();
                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int DeleteOrderDetail(short id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short) Common.RetCode.SUCESS)
                {
                    return (int) Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int) Common.UserType.ADMIN)
                    return (int) Common.RetCode.INCORRECT_AUTHORITY;

                var orderDetail = (from row in DataContext.OrderDetails
                                   where row.OrderDetailId == id
                                   select row).First();

                if (orderDetail == null)
                {
                    return (int) Common.RetCode.INCORRECT_PUBLISHER;
                }

                DataContext.OrderDetails.DeleteOnSubmit(orderDetail);
                DataContext.SubmitChanges();

                return (int) Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int) Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod]
        public OrderDetail GetOrderDetailById(short id)
        {
            var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
            if (_loginUser.Type != (int) Common.UserType.ADMIN)
                return null;
            OnlineShopDataContext DataContext = new OnlineShopDataContext();

            var orderDetail = (from row in DataContext.OrderDetails
                               where row.OrderDetailId == id
                               select row).First();

            return orderDetail;
        }

        [WebMethod]
        public List<OrderDetail> GetListOrderDetailByOrderId(short orderId)
        {
            var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
            if (_loginUser.Type != (int) Common.UserType.ADMIN)
                return null;

            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var orderDetails = from row in DataContext.OrderDetails
                                   where row.OrderId == orderId
                                   select row;
                return orderDetails.ToList();
            }
            catch (Exception)
            {
                return new List<OrderDetail>();
            }
        }

        [WebMethod]
        public List<BSPortal.Usercontrol.Admin.Book.Order.OrderDetailClass> GetListOrderDetailClassByOrderId(
            short orderId)
        {
            var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
            if (_loginUser.Type != (int) Common.UserType.ADMIN)
                return null;

            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var orderDetails = from row in DataContext.OrderDetails
                                   where row.OrderId == orderId
                                   select row;
                List<OrderDetail> listData = orderDetails.ToList();
                List<BSPortal.Usercontrol.Admin.Book.Order.OrderDetailClass> listDetail =
                    new List<BSPortal.Usercontrol.Admin.Book.Order.OrderDetailClass>();
                foreach (var item in listData)
                {
                    BSPortal.Usercontrol.Admin.Book.Order.OrderDetailClass detail =
                        new BSPortal.Usercontrol.Admin.Book.Order.OrderDetailClass();
                    detail.Amount = item.Amount;
                    detail.OrderDetailId = item.OrderDetailId;
                    detail.OrderId = item.OrderId;
                    detail.ProductId = item.ProductId;
                    detail.ProductName = this.GetProductById(item.ProductId).Name;
                    listDetail.Add(detail);
                }
                return listDetail;
            }
            catch (Exception)
            {
                return new List<BSPortal.Usercontrol.Admin.Book.Order.OrderDetailClass>();
            }
        }
        #endregion

        #region HTMLContent
        [WebMethod]
        public List<HTMLContent> GetAllHTMLContent()
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var htmlContent = from row in DataContext.HTMLContents
                              select row;
                return htmlContent.ToList();
            }
            catch (Exception)
            {
                return new List<HTMLContent>();
            }
        }
        [WebMethod]
        public List<HTMLContent> GetListHTMLContentConditionLikeName(string likeName)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var htmlContent = from row in DataContext.HTMLContents
                              where row.Name.IndexOf(likeName) >= 0
                              select row;
                return htmlContent.ToList();
            }
            catch (Exception)
            {
                return new List<HTMLContent>();
            }
        }
        [WebMethod]
        public int DeleteHTMLContent(short p)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var htmlContent = (from row in DataContext.HTMLContents
                              where row.ID == p
                              select row).First();

                if (htmlContent == null)
                {
                    return (int)Common.RetCode.INCORRECT_WRITER;
                }

                DataContext.HTMLContents.DeleteOnSubmit(htmlContent);
                DataContext.SubmitChanges();

                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod]
        public HTMLContent GetHTMLContentById(short p)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();

            var htmlContent = (from row in DataContext.HTMLContents
                          where row.ID == p
                          select row).First();

            return htmlContent;
        }
        [WebMethod]
        public int CreateHTMLContent(string name, string content)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var htmlContent = new HTMLContent { Name = name,  Content = content };

                DataContext.HTMLContents.InsertOnSubmit(htmlContent);
                DataContext.SubmitChanges();

                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }
        [WebMethod]
        public int UpdateHTMLContent(short id,string name, string content)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var htmlContent = (from row in DataContext.HTMLContents
                              where row.ID == id
                              select row).First();

                if (htmlContent == null)
                {
                    return (int)Common.RetCode.INCORRECT_WRITER;
                }

                htmlContent.Name = name;
                htmlContent.Content = content;

                DataContext.SubmitChanges();
                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }
        #endregion

        #region City
        [WebMethod]
        public  List<City> GetAllCity()
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var writers = from row in DataContext.Cities
                              orderby row.Name
                              select row;
                return writers.ToList();
                
            }
            catch (Exception)
            {
                return new List<City>();
            }
        }
        [WebMethod]
        public List<City> GetListCityConditionLikeName(string likeName)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var writers = from row in DataContext.Cities
                              where row.Name.IndexOf(likeName) >= 0
                              orderby row.Name
                              select row;
                return writers.ToList();
            }
            catch (Exception)
            {
                return new List<City>();
            }
        }
        [WebMethod]
        public int DeleteCity(int id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var city = (from row in DataContext.Cities
                              where row.CityId == id
                              select row).First();

                if (city == null)
                {
                    return (int)Common.RetCode.INCORRECT_CITY;
                }

                DataContext.Cities.DeleteOnSubmit(city);
                DataContext.SubmitChanges();

                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int UpdateCity(int id, string name)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var city = (from row in DataContext.Cities
                              where row.CityId == id
                              select row).First();

                if (city == null)
                {
                    return (int)Common.RetCode.INCORRECT_WRITER;
                }

                city.Name = name;

                DataContext.SubmitChanges();
                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int CreateCity(string name)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var city = new City() { Name = name };
                
                DataContext.Cities.InsertOnSubmit(city);
                DataContext.SubmitChanges();
                
                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod]
        public City GetCityById(int id)
        {
            try
            {
                OnlineShopDataContext DataContext = new OnlineShopDataContext();

                var writer = (from row in DataContext.Cities
                              where row.CityId == id
                              select row).FirstOrDefault();
                return writer;
            }
            catch(Exception ex)
            {
                return new City();
            }
        }

        [WebMethod]
        public List<City> GetListCityByDistrictId(int districtId)
        {
            OnlineShopDataContext dataContext = new OnlineShopDataContext();
            try
            {
                var data = from cities in dataContext.Cities
                           join district in dataContext.Districts on cities.CityId equals district.CityId
                           where district.DistrictId == districtId
                           select cities;
                return data.ToList();
            }catch(Exception ex)
            {
                return new List<City>();
            }
        }

        #endregion

        #region District
        [WebMethod]
        public int DeleteDistrict(int id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var writer = (from row in DataContext.Districts
                              where row.DistrictId == id
                              select row).First();

                if (writer == null)
                {
                    return (int)Common.RetCode.INCORRECT_WRITER;
                }

                DataContext.Districts.DeleteOnSubmit(writer);
                DataContext.SubmitChanges();

                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int UpdateDistrict(int districtId, string name, int cityId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var district = (from row in DataContext.Districts
                            where row.DistrictId == districtId
                            select row).First();

                if (district == null)
                {
                    return (int)Common.RetCode.INCORRECT_WRITER;
                }

                district.Name = name;
                district.CityId = cityId;

                DataContext.SubmitChanges();
                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int CreateDistrict(string name, int cityId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var district = new District() { Name = name, CityId = cityId};

                DataContext.Districts.InsertOnSubmit(district);
                DataContext.SubmitChanges();

                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod]
        public List<EntityDistrict> GetListDistrictConditionLikeName(string likeName, int cityId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var writers = from dis in DataContext.Districts
                              join cities in DataContext.Cities on dis.CityId equals cities.CityId 
                              where dis.Name.Trim().IndexOf(likeName.Trim()) >= 0 && (cities.CityId==cityId || cityId == -1)
                              orderby dis.Name
                              select new Entity.EntityDistrict()
                              {
                                  CityName = cities.Name,
                                  DistrictId = dis.DistrictId,
                                  Name = dis.Name
                              };

                return writers.ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }

        [WebMethod]
        public List<EntityDistrict> GetAllDistrict(int cityId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var writers = from dis in DataContext.Districts
                              join cities in DataContext.Cities on dis.CityId equals cities.CityId
                              where cities.CityId==cityId || cityId==-1
                              orderby dis.Name
                              select new Entity.EntityDistrict()
                                         {
                                             CityName = cities.Name,
                                             DistrictId = dis.DistrictId,
                                             Name = dis.Name
                                         };

                return writers.ToList();
            }
            catch (Exception)
            {
                return new List<EntityDistrict>();
            }
        }

        [WebMethod]
        public List<District> GetDistrictByWardId(int wardId)
        {
            OnlineShopDataContext dataContext = new OnlineShopDataContext();
            try
            {
                var data = from dis in dataContext.Districts
                           join ward in dataContext.Wards on dis.DistrictId equals ward.DistrictId
                           where ward.WardId == wardId
                           select dis;
                return data.ToList();
            }catch(Exception ex)
            {
                return new List<District>();
            }
        }

        [WebMethod]
        public District GetDistrictById(int id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();

            var writer = (from row in DataContext.Districts
                          where row.DistrictId == id
                          select row).First();

            return writer;
        }

        #endregion

        #region Ward
        [WebMethod]
        public List<EntityWard> GetAllWard(int cityId, int districtId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var writers = from war in DataContext.Wards
                              join dis in DataContext.Districts on war.DistrictId equals dis.DistrictId
                              join city in DataContext.Cities on dis.CityId equals city.CityId 
                              where (city.CityId == cityId || cityId == -1) && (dis.DistrictId == districtId||districtId==-1)
                              orderby dis.Name
                              select new Entity.EntityWard()
                              {
                                  Name = war.Name,
                                  CityName = city.Name,
                                  DistrictName = dis.Name,
                                  WardId = war.WardId
                              };

                return writers.ToList();
            }
            catch (Exception)
            {
                return new List<EntityWard>();
            }
        }

        [WebMethod]
        public List<EntityWard> GetListWardConditionLikeName(string likeName, int cityId, int districtId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                var writers = from war in DataContext.Wards
                              join dis in DataContext.Districts on war.DistrictId equals dis.DistrictId
                              join city in DataContext.Cities on dis.CityId equals city.CityId
                              where  war.Name.IndexOf(likeName)>=0 && 
                              (city.CityId == cityId || cityId == -1) && (dis.DistrictId == districtId || districtId == -1)
                              orderby dis.Name
                              select new Entity.EntityWard()
                              {
                                  Name = war.Name,
                                  CityName = city.Name,
                                  DistrictName = dis.Name,
                                  WardId = war.WardId
                              };

                return writers.ToList();
            }
            catch (Exception)
            {
                return new List<EntityWard>();
            }
        }

        [WebMethod]
        public int DeleteWard(int id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var writer = (from row in DataContext.Wards
                              where row.WardId == id
                              select row).First();

                if (writer == null)
                {
                    return (int)Common.RetCode.INCORRECT_WRITER;
                }

                DataContext.Wards.DeleteOnSubmit(writer);
                DataContext.SubmitChanges();

                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int UpdateWard(int wardId, string name, int districtId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var district = (from row in DataContext.Wards
                                where row.WardId == wardId
                                select row).First();

                if (district == null)
                {
                    return (int)Common.RetCode.INCORRECT_WRITER;
                }

                district.Name = name;
                district.DistrictId = districtId;


                DataContext.SubmitChanges();
                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod(EnableSession = true)]
        public int CreateWard(string name, int districtId)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();
            try
            {
                if (IsLogin() != (short)Common.RetCode.SUCESS)
                {
                    return (int)Common.RetCode.NOT_LOGIN;
                }

                var _loginUser = GetUserById(System.Web.HttpContext.Current.Session["Username"].ToString());
                if (_loginUser.Type != (int)Common.UserType.ADMIN)
                    return (int)Common.RetCode.INCORRECT_AUTHORITY;

                var ward = new Ward() { Name = name, DistrictId = districtId };

                DataContext.Wards.InsertOnSubmit(ward);
                DataContext.SubmitChanges();

                return (int)Common.RetCode.SUCESS;
            }
            catch (Exception)
            {
                return (int)Common.RetCode.SYSTEM_ERROR;
            }
        }

        [WebMethod]
        public Ward GetWardById(int id)
        {
            OnlineShopDataContext DataContext = new OnlineShopDataContext();

            var writer = (from row in DataContext.Wards
                          where row.WardId == id
                          select row).First();

            return writer;
        }

        #endregion
    }
}